use sqlx::{SqlitePool, Error};
use tracing::info;

#[derive(Debug, sqlx::FromRow)]
pub struct ReviewRecord {
    pub id: i32,
    pub package_hash: String,
    pub status: String,
    pub reject_reason: Option<String>
}

pub struct ReviewService {
    pool: SqlitePool
}

impl ReviewService {
    pub async fn new(database_url: &str) -> Result<Self, Error> {
        let pool = SqlitePool::connect(database_url).await?;
        Ok(Self { pool })
    }

    #[tracing::instrument]
    pub async fn get_review(&self, package_hash: &str) -> Result<ReviewRecord, Error> {
        sqlx::query_as!(
            ReviewRecord,
            "SELECT * FROM reviews WHERE package_hash = ?",
            package_hash
        )
        .fetch_one(&self.pool)
        .await
    }

    #[tracing::instrument]
    pub async fn update_status(
        &self,
        package_hash: &str,
        status: &str,
        reason: Option<&str>
    ) -> Result<(), Error> {
        sqlx::query!(
            "UPDATE reviews SET status = ?, reject_reason = ? WHERE package_hash = ?",
            status,
            reason,
            package_hash
        )
        .execute(&self.pool)
        .await?;
        
        info!(%package_hash, "Review status updated");
        Ok(())
    }
}